package io.yunho.webflux.client.handlers;

import io.yunho.webflux.client.domain.MethodInfo;
import io.yunho.webflux.client.domain.ServerInfo;
import io.yunho.webflux.client.interfaces.RestHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @author: yunho
 * @date: 2021/5/14 18:29
 * @description:
 */
public class WebClientRestHandler implements RestHandler {

    private WebClient webClient;

    //初始化Webclient端
    @Override
    public void init(ServerInfo serverInfo) {
        this.webClient = WebClient.create(serverInfo.getUrl());
    }

    /**
     * 处理Rest请求
     * @param methodInfo
     * @return
     */
    @Override
    public Object invokeRest(MethodInfo methodInfo) {
        Object result =null;
        WebClient.RequestBodySpec accept = this.webClient
                .method(methodInfo.getHttpMethod())
                //url和参数
                .uri(methodInfo.getUrl(), methodInfo.getParams())
                .accept(MediaType.APPLICATION_JSON);
        WebClient.ResponseSpec retrieve =null;
        //判断是否有body
        if(methodInfo.getBody()!=null){
            //发出请求
            retrieve= accept.body(methodInfo.getBody(), methodInfo.getBodyClass()).retrieve();
        }else{
            retrieve = accept.retrieve();
        }
        retrieve.onStatus(status -> status.value()== HttpStatus.NOT_FOUND.value()
                , response -> Mono.just(new RuntimeException("未找到指定对象")));
        //处理flux还是mono
        if(methodInfo.getIsFlux()){
            result=  retrieve.bodyToFlux(methodInfo.getReturnElementType());
        }else{
            result=retrieve.bodyToMono(methodInfo.getReturnElementType());
        }
        //处理body
                

        return result;
    }
}
